package com.syl.springcloud.authorization.config;

import com.syl.springcloud.authorization.bean.ReturnMessage;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * oauth2 资源服务器配置
 * @author syl
 * @create 2018-08-09 16:07
 **/
@Configuration
public class WebResourcesConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources
        .authenticationEntryPoint((request, response, authentication) ->
            returnJson(response,new ReturnMessage(401,authentication.getMessage()))
        )
        .accessDeniedHandler((request, response, authentication) ->
            returnJson(response,new ReturnMessage(403,authentication.getMessage()))
        )
        ;
    }

    private void returnJson(HttpServletResponse response, ReturnMessage msg) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.getWriter().println(new ObjectMapper().writeValueAsString(msg));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
